package com.xiaok.netty.server.tcpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @Classname TCPServer
 * @Description TCPServer 启动类
 * @Date 2020/9/29 20:42
 * @Created by xiaok
 */
@Component
public class TCPServer {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("serverBootstrap")
    private ServerBootstrap serverBootstrap;

    @Autowired
    @Qualifier("tcpSocketAddress")
    private InetSocketAddress inetSocketAddress;

    @Autowired
    @Qualifier("bossGroup")
    private NioEventLoopGroup bossGroup;

    @Autowired
    @Qualifier("workerGroup")
    private NioEventLoopGroup workerGroup;

    private Channel serverChannel;

    public void start()  {
        try {
            ChannelFuture channelFuture = serverBootstrap.bind(inetSocketAddress).sync();
            /**
             * f.channel().closeFuture().sync() 是等待服务端监听端口关闭
             * 该方法进行阻塞,等待服务端链路关闭之后继续执行。
             */
            serverChannel = channelFuture.channel().closeFuture().sync().channel();
            logger.info("服务器关闭了!!!!!!!");
        } catch (InterruptedException e) {
            logger.info("发送中断异常!!!!!!!");
            e.printStackTrace();
        }finally {
            // 优雅的关闭
            logger.info("服务端优雅的关闭!");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void stop() throws Exception {
        // 关闭 IO 通道 和 连接 通道
        serverChannel.close();
        serverChannel.parent().close();
    }
    public ServerBootstrap getServerBootstrap() {
        return serverBootstrap;
    }

    public void setServerBootstrap(ServerBootstrap serverBootstrap) {
        this.serverBootstrap = serverBootstrap;
    }

    public InetSocketAddress getTcpPort() {
        return inetSocketAddress;
    }

    public void setTcpPort(InetSocketAddress inetSocketAddress) {
        this.inetSocketAddress = inetSocketAddress;
    }
}
